<template>
    <div class="equipmentDataManagement mt16">
      <searchPrams @search="changeNum" :type="2" :ifFinish="ifFinish"/>
      <div class="list-layout mt16">
        <div class="btns clear" >
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏'):$t('隐藏操作栏') }}</Button>
        </div>
        <div class="tableContent">
          <Table
              class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
              ref="selection"
              row-key="deviceScrapApprovalId"
              :columns="columnsList"
              :data="dataSource"
              @on-selection-change="handleSelectionChange">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn"
                    v-has="'approvalCheck'"
                    @click="handleledgerDetail(row)">
                <i class="iconfont zy-common-chakan"></i>
                <span>{{ $t('common.Check') }}</span>
              </span>

<!--              <span v-if="ifFinish === 0 && row.approvalStatus === 7"
                    class="operationBtn"
                    @click="updateInfo(row)">
                <i class="iconfont zy-common-bianji"></i>
                <span>{{ $t('common.Edit') }}</span>
              </span>-->
<template v-if="ifFinish === 0 && row.approvalStatus === 3">
   <span
       class="operationBtn"
       v-has="'scrapApplyDoApproval'"
       @click="approval(row)">
                <i class="iconfont zy-common-chenggong1"></i>
                <span>{{ $t('common.Approval') }}</span>
              </span>
</template>
            </template>
          </Table>
        </div>
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="ids.length" />
          <Page :total="total"
                :page-size="pageSize"
                :page-size-opts="$variable.pageSizes"
                :current="pageNum"
                @on-change="changePageNum"
                @on-page-size-change="changePageSize"
                show-sizer show-total/>
        </div>
      </div>
        <!--批量导入-->
        <import-excel-modal
            :isUpdate="isUpdate"
            :importExcelStateF="importExcelState"
            v-if="importExcelState"
            @importExcelChange="importExcelChange"
        />
        <!--新增报废-->
        <approval :show.sync="approvalShow" :row.sync="row" @change="searchList"/>
        <edit :show.sync="editShow" :row.sync="row" @change="searchList"/>
    </div>
</template>

<script>
import { findOrgByToken } from '@/api/index.js';
import importExcelModal from '@/components/importExcel.vue';
import toggleTableOperation from "@/mixins/toggleTableOperation";
import recursion from '@/util/recursion';
import fileDownload from 'js-file-download';
import approval from './approval';
import edit from './edit';
import searchPrams from "./searchPrams";
export default {
    name: "Scrapapplication",
    mixins:[toggleTableOperation],
    components: {
        importExcelModal,
        approval,
        edit,
        searchPrams
    },
    props: ['ifFinish'],
    watch:{
      ifFinish:function (val){
        if (val==1){
          this.customCacheKey = "ScrapapplicationFinish"
        }else{
          this.customCacheKey = "ScrapapplicationUnfinish"
        }
        this.getTableColumnsWidth(this.columns)
      }
    },
    data() {
        return {
            customCacheKey:"ScrapapplicationUnfinish",
            editShow: false,
            row: {},
            isUpdate: false,//是否台账更新
            status: '',
            delId: '',
            delDeviceId: '',//台账删除
            uploadId: '',
            tagName: '',
            total: 0,
            pageNum: 1,
            pageSize: 10,
            approvalShow: false,//删除模态框显示
            delDeviceLoading: false,
            uploadVisible: false,
            importExcelState: false,
            writeVisible: false,
            loading: false,
            uploadLoading: false,
            approvalLoading: false,
            delelteVisible: false,
            searchParams: {},
            checkBtnPermission: {},
            formItem: {
                deviceNo: ''
            },
            validateWritefunction: {
                deviceNo: [
                    {required: true, message: '请输入机台号', trigger: 'blur'}
                ],
            },
            pageSizeOption: [10, 20, 30],
            statusList: [{id: 0, name: '全部'}, {id: 2, name: '已到位待安调'}, {id: 3, name: '安调中'}, {id: 4, name: '已安调待验收'}, {id: 5, name: '验收中'}, {id: 6, name: '已验收'}, {id: 7, name: '已入账'}],
            resultList: [{id: 0, name: '全部'}, {id: 1, name: '在用'}, {id: 2, name: '闲置'}, {id: 3, name: '报废'}],
            columns: [
                // {
                //   type: 'selection',
                //   minWidth: 60,
                //   align: 'center'
                // },
                {
                    title: `${this.$t('equipmentscrapped.ID')}`,
                    key: 'deviceScrapApplyNo',
                    align: 'center',
                    minWidth: 150,
                    resizable: true
                },
                {
                    //title: '审批状态',
                    title: `${this.$t('common.ApprovalStatus')}`,
                    key: 'approvalStatusStr',
                    align: 'center',
                    minWidth: 140,
                  resizable: true
                },
                {
                    title: `${this.$t('maintenance.EquipmentNo')}`,
                    key: 'deviceNo',
                    align: 'center',
                    minWidth: 140,
                  resizable: true
                },
                {
                    title: `${this.$t('maintenance.EquipmentName')}`,
                    key: 'deviceName',
                    align: 'center',
                    minWidth: 140,
                  resizable: true
                },
                {
                    title: `${this.$t('common.company')}`,
                    key: 'companyName',
                    align: 'center',
                    minWidth: 150,
                  resizable: true
                },
                {
                    title: `${this.$t('common.Installation')}`,
                    key: 'position6',
                    align: 'center',
                    minWidth: 150,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.From')}`,
                    key: 'sblyStr',
                    align: 'center',
                    minWidth: 120,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.AssetNo')}`,
                    key: 'assetsNo',
                    align: 'center',
                    minWidth: 120,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.DepreciationLife')}`,
                    key: 'depreciation',
                    align: 'center',
                    minWidth: 150,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.UsedLife')}`,
                    key: 'useTime',
                    align: 'center',
                    minWidth: 150,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.OriginalValue')}`,
                    key: 'assetsOriginal',
                    align: 'center',
                    minWidth: 260,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.ResidualValue')}`,
                    key: 'assets',
                    align: 'center',
                    minWidth: 130,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.UsedDept')}`,
                    key: 'useDept',
                    align: 'center',
                    minWidth: 120,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.DepartmentalCostCenter')}`,
                    key: 'deptCostCenter',
                    align: 'center',
                    minWidth: 220,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.ApplyBy')}`,
                    key: 'applyBy',
                    align: 'center',
                    minWidth: 120,
                  resizable: true
                },
                {
                    title: `${this.$t('equipmentscrapped.ApplyTime')}`,
                    key: 'applyDateTime',
                    align: 'center',
                    minWidth: 150,
                  resizable: true
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    minWidth: this.util.autoWidth(250,280),
                    align: "center",
                    fixed: 'right',
                }
            ],
            dataSource: [],
            tagList: [{id: '', name: '全部'}],
            orgList: [],
            fileList: [],
            showFileList: [],
            ids: [],
            deviceList: [
                {label: 'A类', value: 'A'},
                {label: 'B类', value: 'B'},
                {label: 'C类', value: 'C'},
            ],
            boxs: [{label: '是', value: '1'}, {label: '否', value: '2'}],
            isEdit: false
        }
    },
    created() {

      if (this.ifFinish==1){
        this.customCacheKey = "ScrapapplicationFinish"
      }else{
        this.customCacheKey = "ScrapapplicationUnfinish"
      }
      this.getTableColumnsWidth(this.columns)

        this.getCompanyList()
        this.getOrgList()
    },
    mounted() {
        this.searchList()
        let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
        for (let item of itemList) {
            if (item.code == "dmsDeviceTzGetDevicePrint") {
                this.checkBtnPermission.dmsDeviceTzGetDevicePrint = true
            }
            if (item.code == 'dmsDeviceTzTemplate') {
                this.checkBtnPermission.dmsDeviceTzTemplate = true
            }
            if (item.code == 'dmsDeviceTzGetDeviceTzList') {
                this.checkBtnPermission.dmsDeviceTzGetDeviceTzList = true
            }
            if (item.code == 'dmsDeviceTzGetTzDetailByDeviceEq') {
                this.checkBtnPermission.dmsDeviceTzGetTzDetailByDeviceEq = true
            }
            if (item.code == 'dmsDeviceTzImport') {
                this.checkBtnPermission.dmsDeviceTzImport = true
            }
            if (item.code == 'dmsDeviceTzExportTz') {
                this.checkBtnPermission.dmsDeviceTzExportTz = true
            }
            if (item.code == 'dmsDeviceTzUpdateDeviceNo') {
                this.checkBtnPermission.dmsDeviceTzUpdateDeviceNo = true
            }
            if (item.code == 'dmsDeviceTzAddFiles') {
                this.checkBtnPermission.dmsDeviceTzAddFiles = true
            }
            if (item.code == 'dmsDeviceTzGetBatchDevicePrint') {
                this.checkBtnPermission.dmsDeviceTzGetBatchDevicePrint = true
            }
            if (item.code == 'dmsDeviceTzDeleteById') {
                this.checkBtnPermission.dmsDeviceTzDeleteById = true
            }
            if (item.code == 'dmsDeviceTzDeleteByIds') {
                this.checkBtnPermission.dmsDeviceTzDeleteByIds = true
            }
            if (item.code == 'dmsDeviceTzUpdateDevice') {
                this.checkBtnPermission.dmsDeviceTzUpdateDevice = true
            }
            if (item.code == 'dmsDeviceTzImportUpdate') {
                this.checkBtnPermission.dmsDeviceTzImportUpdate = true
            }
        }
    },
    methods: {
        handleCasChange(val, selectedData) {
            this.searchParams.orgId = val[val.length - 1]
            // this.formItem.orgName = selectedData[selectedData.length - 1].label
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === 'success') {
                this.changeNum();
            }

        },
        handleChangeTab(name) {
            console.log(name)
            this.tagName = name
            this.searchParams = {}
            this.searchList()
        },
        exportTemplate() {
            const filName = '设备台账模板'
            this.axios({
                method: 'get',
                url: '/dms/dmsDeviceTz/template',
                responseType: 'blob',
                params: {}
            }).then(res => {
                
                fileDownload(res, filName + '.xlsx')
            })

        },
        exportTemplateClick() {
            let params = {};
            for (let key in this.searchParams) {
                if (key === 'orgId' && this.searchParams['orgId']) {
                    const arr = this.searchParams[key]
                    const {length, last = length - 1} = arr
                    this.$set(params, key, arr[last])
                } else {
                    if (this.searchParams[key]) {
                        this.$set(params, key, this.searchParams[key])
                    }
                }
            }
            const filName = '设备台账'
            this.axios({
                method: 'post',
                url: '/dms/dmsDeviceTz/exportTz',
                responseType: 'blob',
                data: {...params}
            }).then(res => {
                fileDownload(res, filName + '.xlsx')
            })

        },
        handleUpdateDeviceNo(row) {
            this.id = row.id
            this.formItem.deviceNo = row.deviceNo
            this.orgIdinfo = row.orgId
            this.writeVisible = true
        },
        handlePreview(item) {
            if (item.filePath) {
                window.open(this.util.filePathToUrl(item.filePath))
            }
        },
        delFileList(id) {
            this.delelteVisible = true
            this.delId = id
        },
        handleUpload(file) {
            this.uploadLoading = true
            console.log(file)
            // let tmpList = []
            // this.fileList.push({
            //     fileName: file.name
            // })
            console.log(this.fileList)
            // tmpList.push({
            //     fileName: file.name
            // })
            // this.showFileList = [...this.showFileList, ...tmpList]
            let formData = new FormData();
            formData.append("dir", 'device')
            formData.append("file", file);
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            };
            this.axios({
                method: 'post',
                url: '/fileServer/upload',
                data: formData,
                config,
            }).then(res => {
                
                if (res.code == 200) {
                    let dmsAttachmentList = []
                    dmsAttachmentList.push({
                        deviceMId: this.uploadId,
                        fileName: res.data.fileName,
                        filePath: res.data.filepath,
                        fileUrl: res.data.fileUrl
                    })
                    // let dmsAttachmentList = res.data.map(item => {
                    //     return {
                    //         deviceMId: this.uploadId,
                    //         fileName: item.fileName,
                    //         filePath: item.filepath,
                    //         fileUrl: item.fileUrl
                    //     }
                    // })
                    this.axios({
                        method: 'post',
                        url: '/dms/dmsDeviceTz/addFiles',
                        data: dmsAttachmentList
                    }).then(res => {
                        
                        if (res.code == 200) {
                            this.getUploadFile()
                            this.$Message.success('上传成功')
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                        }
                    }).finally(() => {
                        this.uploadLoading = false
                        // this.uploadVisible = false
                    });
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                }
            }).catch(() => {
                this.uploadLoading = false
            });
            return false;
        },
        handleManyFile(row) {
            this.uploadVisible = true
            this.uploadId = row.deviceMId
            // this.fileList = []
            this.getUploadFile()
        },
        getUploadFile() {
            this.axios({
                method: 'get',
                url: '/dms/dmsAttachment/get',
                params: {
                    deviceMId: this.uploadId,
                    type: 2
                }
            }).then(res => {
                
                if (res.code == 200) {
                    this.fileList = res.data.map(item => {
                        return {
                            id: item.id,
                            fileName: item.file_name,
                            fileUrl: item.file_url
                        }
                    })
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                }
            }).finally(() => {

            });
        },
        handleapprovalOk() {
            this.approvalLoading = true
            this.axios({
                method: 'get',
                url: '/dms/dmsAttachment/del',
                params: {
                    id: this.delId
                }
            }).then(res => {
                
                if (res.code == 200) {
                    this.getUploadFile()
                    this.$Message.success(({content: '删除成功！', duration: 6, closable: true}))
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                }
            }).finally(() => {
                this.approvalLoading = false
                this.delelteVisible = false
            });
        },
        handleOk() {
            this.loading = true
            this.axios({
                method: 'post',
                url: '/dms/dmsDeviceTz/updateDeviceNo',
                data: {
                    id: this.id,
                    orgId: this.orgIdinfo,
                    deviceNo: this.formItem.deviceNo
                }
            }).then(res => {
                
                if (res.code === 200) {
                    this.$Message.success(({content: '修改成功', duration: 3, closable: true}));
                    this.searchList()
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.loading = false
                this.writeVisible = false
            })

        },
        //批量导入
        handleBatchImport(status) {
            this.isUpdate = status == 1 ? true : false
            this.importExcelState = true;

        },
        //批量打印
        handleBatchPrint() {
            this.$refs.ledgerBatchPrintModal.show(this.ids)
        },
        handleChangeVisible() {
            this.$refs.selection.selectAll(false);
        },
        //批量操作
        handleSelectionChange(selectionData) {
            console.log(selectionData)
            let arr = []
            selectionData.forEach(item => {
                arr.push(item.id)
            })
            this.ids = arr
        },
        //分页
        changeNum(params) {
            this.pageNum = 1;
            this.searchList(params);
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        searchList(_params) {
            let params = {
                companyId: this.tagName ? this.tagName : '',
                pageNo: this.pageNum,
                pageSize: this.pageSize,
                ifFinish: this.ifFinish
            };
            for (let key in _params) {
                if (key === 'orgId' && _params['orgId']) {
                    const arr = _params[key]
                    const {length, last = length - 1} = arr
                    this.$set(params, key, arr[last])
                } else {
                    if (_params[key]) {
                        this.$set(params, key, _params[key])
                    }
                }

            }
            this.axios({
                method: 'post',
                url: '/dms/scrapApply/approvalList',
                data: params
            }).then(res => {
                if (res.code === 200) {
                    this.dataSource = res.data.list
                    /*res.data.list.forEach(val => {
                        if (val.categoryName) {
                            val.categoryName = val.categoryName + '类'
                        }
                    })*/
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        //公司列表
        getCompanyList() {
            this.axios({
                method: 'get',
                url: '/basic/company/getCompanyListByUser',
                params: {}
            }).then(res => {
                if (res.code === 200) {
                    let arr = res.data.map(item => {
                        return {
                            ...item,
                            id: item.id.toString()
                        }
                    })
                    this.tagList = [...this.tagList, ...arr]
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        getOrgList() {
            let params = {
                level: 3
            }
            findOrgByToken(params).then(res => {
                if (res.code === 200) {
                    const obj = {
                        label: 'name',
                        value: 'code',
                        children: 'children'
                    }
                    this.orgList = recursion.convertTree(res.data, obj)
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        //设备类别
        getDeviceList() {
            this.axios({
                method: 'get',
                url: '/dms/dmsCategory/getSelectList',
                params: {}
            }).then(res => {
                if (res.code === 200) {
                    // res.data.forEach(val=>{
                    //   switch (val['label']) {
                    //     case 'MME':
                    //       val.label = 'A类'
                    //           break;
                    //     case 'HME':
                    //       val.label = 'B类'
                    //       break;
                    //     case 'AME':
                    //       val.label = 'C类'
                    //       break;
                    //   }
                    // })
                    this.deviceList = res.data
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        handleledgerScore({deviceMId, assetsNo, id}) {
            this.$router.push({
                path: '/devBasic/equipmentsLedgerManagement/equipmentScore',
                query: {
                    deviceMId,
                    assetsNo,
                    id,
                    status: 'score'
                }
            })
        },
        //详情页
        handleledgerDetail({id}) {
            this.$router.push({
                path: '/devBasic/equipmentscrapped/scrapapplicationDetail',
                query: {
                    id,
                }
            })
        },
        handlePrint(record) {
            this.$refs.ledgerPrintModal.show(record)
        },
        //审核
        approval(record) {
            this.row = record
            this.approvalShow = true
        },
        //批量删除
        handleMulDelete() {
            this.status = 1
            this.approvalShow = true
        },
        approvalOk() {
            this.approvalLoading = true
            if (this.status == 0) {
                this.axios({
                    method: 'post',
                    url: '/scrapApply/doApproval',
                    params: {
                        id: this.delDeviceId
                    }
                }).then(res => {
                    
                    if (res.code === 200) {
                        this.searchList()
                        this.$Message.success(({content: '审批成功！', duration: 2, closable: true}));
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.approvalLoading = false
                    this.approvalShow = false
                })
            } else {
                this.axios({
                    method: 'post',
                    url: '/dms/dmsDeviceTz/deleteByIds',
                    params: {
                        ids: String(this.ids)
                    }
                }).then(res => {
                    
                    if (res.code === 200) {
                        this.searchList()
                        this.$Message.success(({content: '批量删除成功！', duration: 2, closable: true}));
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.approvalLoading = false
                    this.approvalShow = false
                })
            }

        },
        updateInfo(record) {
            this.editShow = true
            this.row = record
        },
    }

}
</script>

<style scoped lang="scss">
::v-deep .ivu-upload-drag {
    border: none !important;
}

.equipmentDataManagement {
    .ivu-tabs.ivu-tabs-card {
        .ivu-tabs-tab {
            width: 120px !important;
            text-align: center;
        }

        ::v-deep .ivu-tabs-tab.ivu-tabs-tab-active {
            color: #ffffff;
            background-color: #2d8cf0;
        }
    }
}

.file-list {
    /*margin: 20px;*/
    .item-src {
        width: 80%;
        display: inline-block;
        line-height: 26px;
        color: #187bdb;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .item-icon {
        width: 20%;
        display: inline-block;
        margin-top: 4px;
    }
}

</style>
